package smedi.ismedi.web.bff.controller.pesonnel;

import com.smedi.ismedi.constructionproject.api.dto.response.ProjectAssignmentResponse;
import com.smedi.ismedi.constructionproject.api.dto.response.ProjectBasicResponse;
import com.smedi.ismedi.constructionproject.api.feign.RemoteConstructionProjectFeignApi;
import com.smedi.ismedi.constructionproject.api.feign.RemoteProjectAssignmentFeignApi;
import com.smedi.ismedi.organization.api.dto.response.HrOrganizationResponse;
import com.smedi.ismedi.organization.api.dto.response.ProjectOrganizationResponse;
import com.smedi.ismedi.organization.api.feign.RemoteHrOrganizationFeignApi;
import com.smedi.ismedi.organization.api.feign.RemoteProjectOrganizationFeignApi;
import com.smedi.ismedi.personnel.api.dto.response.InternalPersonAssignmentResponse;
import com.smedi.ismedi.personnel.api.feign.RemotePersonCoreFeignApi;
import com.smedi.ismedi.web.starter.common.PaginationData;
import com.smedi.ismedi.web.starter.common.ResponseData;
import com.smedi.ismedi.web.starter.exception.LogicException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import smedi.ismedi.web.bff.controller.BaseController;
import smedi.ismedi.web.bff.dto.HrOrganizationPickerPageResponse;
import smedi.ismedi.web.bff.dto.PersonPickerResponse;
import smedi.ismedi.web.bff.dto.ProjectOrganizationPickerPageResponse;
import smedi.ismedi.web.bff.infrastructure.constant.CustomError;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xulinjun
 * @Date: 2021-6-30 9:46
 */
@Slf4j
@RestController
@Api(tags = {"移动端选择人员和组织接口"})
@RequestMapping("webbff/v1/personPicker")
@AllArgsConstructor
public class PersonPickerController extends BaseController {
    private final RemoteHrOrganizationFeignApi remoteHrOrganizationFeignApi;

    private final RemotePersonCoreFeignApi remotePersonCoreFeignApi;

    private final RemoteProjectAssignmentFeignApi remoteProjectAssignmentFeignApi;

    private final RemoteProjectOrganizationFeignApi remoteProjectOrganizationFeignApi;

    private final RemoteConstructionProjectFeignApi remoteConstructionProjectFeignApi;

    public final static String skipSqlPermission = "ismedi-skip-sql-permission";

    private void setSkipSqlPermission() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        request.getSession().setAttribute(skipSqlPermission, true);
    }

    /**
     * 移动端页面企业组织人员查询页面初始化加载
     *
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "移动端页面企业组织人员查询页面初始化加载")
    @GetMapping(value = "/hrOrganization/initLeftOrganizationList")
    public ResponseData<HrOrganizationPickerPageResponse> getInitHrOrganizationLeftOrganizationList() {
        setSkipSqlPermission();

        HrOrganizationPickerPageResponse dto = new HrOrganizationPickerPageResponse();
        // 获取企业组织信息
        ResponseData<List<HrOrganizationResponse>> responseData = remoteHrOrganizationFeignApi.getHrOrganizationTree(null);
        if (!responseData.isSuccess()) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, responseData.getApplication(), String.valueOf(responseData.getErrorMsg()));
        }

        List<HrOrganizationResponse> list = responseData.getData();
        if (list.size() > 0) {
            // 根节点数据
            HrOrganizationResponse root = list.get(0);
            dto.setRootHrOrganization(root);

            // 二级层级组织
            List<HrOrganizationResponse> levelTwo = new ArrayList<>();
            root.getHrOrganizationChildren().stream().forEach(hrOrganizationResponse -> {
                hrOrganizationResponse.setHrOrganizationChildren(new ArrayList<>());
                levelTwo.add(hrOrganizationResponse);
            });
            dto.setLevelTwoHrOrganizations(levelTwo);

            root.setHrOrganizationChildren(new ArrayList<>()); // 清空子组织
        }

        return new ResponseData<HrOrganizationPickerPageResponse>().success(dto);
    }

    /**
     * 移动端页面企业组织人员查询页面根据人员姓名、企业组织id获取人员清单
     *
     * @param offset
     * @param pageSize
     * @param hrOrganizationId
     * @param lastName
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "移动端页面企业组织人员查询页面根据人员姓名、企业组织id获取人员清单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "offset", value = "页码", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页行数", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(paramType = "query", name = "hrOrganizationId", value = "企业项目id", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(paramType = "query", name = "lastName", value = "人员姓名", dataType = "String", dataTypeClass = String.class)
    })
    @GetMapping(value = "/hrOrganization/getPersonByLevelTwoHrOrganization")
    public ResponseData<PaginationData<PersonPickerResponse>> getPersonByLevelTwoHrOrganization(@RequestParam("offset") Long offset,
                                                                                                @RequestParam("pageSize") Long pageSize,
                                                                                                @RequestParam("hrOrganizationId") Long hrOrganizationId,
                                                                                                @RequestParam(value = "lastName", required = false) String lastName) {
        setSkipSqlPermission();

        ResponseData<PaginationData<InternalPersonAssignmentResponse>> responseData = remotePersonCoreFeignApi.getQueryInternalPersonInfoPagination(offset, pageSize, hrOrganizationId, lastName, null, null, true);
        if (!responseData.isSuccess()) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, responseData.getApplication(), String.valueOf(responseData.getErrorMsg()));
        }

        List<InternalPersonAssignmentResponse> records = responseData.getData().getRecords();
        List<PersonPickerResponse> list = new ArrayList<>();
        records.forEach(data -> list.add(new PersonPickerResponse()
                .setPersonId(data.getPersonId())
                .setMobile(data.getMobile())
                .setLastName(data.getLastName())
                .setInternalJobNames(data.getInternalJobNames())
                .setEmployeeNum(data.getEmployeeNum())));
        PaginationData<PersonPickerResponse> pagination = new PaginationData<PersonPickerResponse>()
                .setCurrent(responseData.getData().getCurrent())
                .setPages(responseData.getData().getPages())
                .setSize(responseData.getData().getSize())
                .setTotal(responseData.getData().getTotal())
                .setRecords(list);

        return new ResponseData<PaginationData<PersonPickerResponse>>().success(pagination);
    }

    /**
     * 移动端页面项目组织人员查询页面初始化加载
     *
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "移动端页面项目组织人员查询页面初始化加载")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "projectId", value = "项目id", dataType = "Long", dataTypeClass = Long.class)
    })
    @GetMapping(value = "/projectOrganization/initLeftOrganizationList")
    public ResponseData<ProjectOrganizationPickerPageResponse> initProjectOrganizationLeftOrganizationList(@RequestParam("projectId") Long projectId) {
        setSkipSqlPermission();

        ProjectOrganizationPickerPageResponse dto = new ProjectOrganizationPickerPageResponse();

        // 获取项目信息
        ResponseData<ProjectBasicResponse> responseData = remoteConstructionProjectFeignApi.getQueryProjectBasicView(projectId);
        if (!responseData.isSuccess()) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, responseData.getApplication(), String.valueOf(responseData.getErrorMsg()));
        }

        ProjectBasicResponse projectBasic = responseData.getData();
        dto.setProjectId(projectBasic.getProjectId())
                .setProjectName(projectBasic.getProjectName())
                .setProjectShortName(projectBasic.getProjectShortName());

        // 获取项目下面的组织信息
        ResponseData<List<ProjectOrganizationResponse>> response = remoteProjectOrganizationFeignApi.getProjectOrganizationTreeRootIsProjectOrganization(projectId);
        if (!response.isSuccess()) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, response.getApplication(), String.valueOf(response.getErrorMsg()));
        }
        List<ProjectOrganizationResponse> levelTwo = new ArrayList<>();
        response.getData().stream().forEach(projectOrganizationResponse -> {
            projectOrganizationResponse.setProjectOrganizationChildren(new ArrayList<>());
            levelTwo.add(projectOrganizationResponse);
        });
        dto.setLevelTwoProjectOrganizations(levelTwo);

        return new ResponseData<ProjectOrganizationPickerPageResponse>().success(dto);
    }

    /**
     * 移动端页面项目组织人员查询页面根据人员姓名、项目组织id获取人员清单
     *
     * @param offset
     * @param pageSize
     * @param projectId
     * @param projectOrganizationId
     * @param lastName
     * @param containProjectOrganizationChildren
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "移动端页面项目组织人员查询页面根据人员姓名、项目组织id获取人员清单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "offset", value = "页码", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页行数", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(paramType = "query", name = "projectId", value = "项目项目id", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(paramType = "query", name = "projectOrganizationId", value = "项目组织id", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(paramType = "query", name = "lastName", value = "人员姓名", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(paramType = "query", name = "containProjectOrganizationChildren", value = "是否包含下级", dataType = "boolean", dataTypeClass = Boolean.class),
    })
    @GetMapping(value = "/hrOrganization/getPersonByLevelTwoProjectOrganization")
    public ResponseData<PaginationData<PersonPickerResponse>> getPersonByLevelTwoProjectOrganization(@RequestParam("offset") Long offset,
                                                                                                     @RequestParam("pageSize") Long pageSize,
                                                                                                     @RequestParam("projectId") Long projectId,
                                                                                                     @RequestParam(value = "projectOrganizationId", required = false) Long projectOrganizationId,
                                                                                                     @RequestParam(value = "lastName", required = false) String lastName,
                                                                                                     @RequestParam(value = "containProjectOrganizationChildren", required = false) boolean containProjectOrganizationChildren) {
        setSkipSqlPermission();

        ResponseData<PaginationData<ProjectAssignmentResponse>> responseData = remoteProjectAssignmentFeignApi.getQueryProjectAssignmentPersonInfoPagination(offset, pageSize, projectId, projectOrganizationId, lastName, null, null, null, containProjectOrganizationChildren);
        if (!responseData.isSuccess()) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, responseData.getApplication(), String.valueOf(responseData.getErrorMsg()));
        }

        List<ProjectAssignmentResponse> records = responseData.getData().getRecords();
        List<PersonPickerResponse> list = new ArrayList<>();
        records.stream().forEach(data -> {
            list.add(new PersonPickerResponse()
                    .setPersonId(data.getPersonId())
                    .setMobile(data.getMobile())
                    .setLastName(data.getLastName())
                    .setProjectJobNames(data.getProjectJob())
                    .setEmployeeNum(data.getEmployeeNum()));
        });

        PaginationData<PersonPickerResponse> pagination = new PaginationData<PersonPickerResponse>()
                .setCurrent(responseData.getData().getCurrent())
                .setPages(responseData.getData().getPages())
                .setSize(responseData.getData().getSize())
                .setTotal(responseData.getData().getTotal())
                .setRecords(list);

        return new ResponseData<PaginationData<PersonPickerResponse>>().success(pagination);
    }
}
